<template>
    <div class="page page-vehicles">
        <v-table
            ref="vTable"
            v-model="list"
            :height="compact ? '350' : 'auto'"
            :columns="columns"
            :func="getList"
            :showPagination="false"
            :compact="compact"
            :multiple="multipleEnabled"
            @selectionChange="handleSelectionChange"
            showCheckbox
            showIndex
        >
            <template #opts>
                <p-list-buttons
                    ref="btns"
                    module="vehicles"
                    :buttons="buttons"
                    :compact="compact"
                    :ids="selectedVehicles"
                    :list="list"
                    @clearIds="handleClearIds"
                    @editEnableChange="() => $emit('editEnableChange', true)"
                    :beforeDeleteFunc="beforeDeleteFunc"
                ></p-list-buttons>
            </template>
        </v-table>
    </div>
</template>

<script type="text/ecmascript-6">
import * as enums from '../../../store/status-enums.js';
import * as Chef from '../../../core/Chef.js';
import * as API from '../../../core/api.js';
import { mapState } from 'vuex';
import _ from 'lodash';
import bus from '../../../utils/Eventbus.js';
import vTable from '../../../utils/v-table/index.js';
import pListButtons from '../p-list-buttons.vue';
import Kernel from '../../../core/Kernel.js';

export default {
    name: 'vehicles',
    components: { vTable, pListButtons },
    props: {
        compact: Boolean // 紧凑模式
    },
    data () {
        return {
            list: [],
            columns: [
                { label: 'icon icon-lock', prop: 'lockExt', width: 30, isIcon: true, align: 'center' },
                { label: this.$t('lang.name'), prop: 'id', width: 120, sortable: true },
                { label: this.$t('lang.status'), prop: 'onlineExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.energy'), prop: 'batteryExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.alert'), prop: 'alertExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.stopIt'), prop: 'stopExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.remote'), prop: 'remoteExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.simulate'), prop: 'simulateExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.response'), prop: 'responseExt', width: 80 },
                { label: this.$t('lang.update'), prop: 'updateExt', width: 70, isBranchground: true },
                { label: this.$t('lang.mileage') + ' [km]', prop: 'mileageExt', width: 100, align: 'right' },
                { label: this.$t('lang.jobTime'), prop: 'jobtimeExt', width: 80 },
                { label: this.$t('lang.location'), prop: 'locationExt', width: 80, isBranchground: true },
                { label: this.$t('lang.destination'), prop: 'destinationExt', width: 90, isBranchground: true },

                { label: this.$t('lang.initTime'), prop: 'initTimeExt', width: 130 },
                { label: this.$t('lang.modified'), prop: 'modificationTimeExt', width: 130 },
                { label: this.$t('lang.responsibility'), prop: 'responsibility', width: 110 },
                {
                    label: this.$t('lang.operate'),
                    fixed: 'right',
                    width: 180,
                    align: 'center',
                    opts: [
                        { label: this.$t('lang.detail'), type: 'info', icon: 'el-icon-document', callback: this.handleDetail },
                        { label: this.$t('lang.edit'), type: 'primary', icon: 'el-icon-edit', callback: this.handleModify },
                        { label: this.$t('lang.lock'), type: 'warning', icon: 'el-icon-lock', callback: this.handleLock },
                        { label: this.$t('lang.delete'), type: 'danger', icon: 'el-icon-delete', callback: this.handleDelete }
                    ]
                }
            ],
            buttons: ['create', 'edit', 'delete', 'lock', 'upload', 'download'],
            disableOpts: false
        };
    },
    computed: {
        ...mapState({
            openedBoxes: state => state.businessStatus.openedBoxes,
            isAltFnActive: state => state.businessStatus.isAltFnActive,
            selectedVehicles: state => state.businessStatus.selectedVehicles
        }),
        multipleEnabled() {
            return this.compact ? this.isAltFnActive : true;
        }
    },
    watch: {
        compact: { handler () { this.init(); }, deep: true },
        // selectedVehicles(val) {
        //     if (this.compact && val && val.length) this.toggleRowSelection(val);
        // },
        // '$root.ws.serverTime'() {
        //     this.initAsync();
        // }
    },
    created() {
        bus.on(`${this.$options.name}.toggleRowSelection`, this.toggleRowSelection);
    },
    mounted() {
        this.init();
    },
    beforeUnmount() {
        this.$store.commit(enums.DESELECT_VEHICLES_ALL);
        bus.off(`${this.$options.name}.toggleRowSelection`, this.toggleRowSelection);
        if (this.kernel) this.kernel.off('handleIncrement', this.handleIncrementFunc);
    },
    methods: {
        init() {
            // hide the opts columns in compact mode.
            let idx = this.columns.findIndex(v => v.opts);
            if (this.compact && idx >= 0) this.columns[idx].hidden = true;
            else if (idx >= 0) this.columns[idx].true = false;
            this.kernel = Kernel.getInstance();
            this.kernel.on('handleIncrement', this.handleIncrementFunc);
        },

        handleIncrementFunc(res) {
            if (!res || !res.refreshTypes || !res.refreshTypes[this.$options.name]) return;
            this.initAsync();
        },
        initAsync: _.throttle(function() {
            if (!this.$root.resources.vehicles) this.$root.resources.vehicles = [];
            if (this.compact && this.openedBoxes.indexOf(`${this.$options.name}Table`) < 0) return;
            if (this.list.length !== this.$root.resources.vehicles.length) {
                if (!this.$root.resources.vehicles && this.list.length === 0) return;
                if (this.$refs.vTable && this.$refs.vTable.truename) bus.emit(`${this.$refs.vTable.truename}.init`);
                return;
            }
            if (this.$root.resources.vehicles.length < 1) return;
            this.list.forEach(v => Chef.extendVehicleAsync(v, this.$root.resources.vehicles));
        }, 1000),
        getList() {
            return API.getLocalResources('vehicles').then(res => {
                let rtn = {...res};
                if (res && res.list && res.list.length) rtn.list = Chef.extendVehicles(res.list, this.$root.resources.models);
                return rtn;
            });
            // return Promise.resolve({ list: [] });
        },
        beforeDeleteFunc(ids) {
            if (ids && ids.length > 0) {
                ids.map(id => {
                    if (this.isRaning(id)) bus.emit('p-vehicle-remote-detail.stop', id);
                });
            }
        },
        isRaning(id) {
            let row = this.list.find(o => o.id === id);
            return row.remoteId !== 'FREE';
        },
        // Trigger from table
        handleSelectionChange(ids) {
            // if (!this.selectedVehicles) this.selectedVehicles = [];
            // return, when its same...
            if (this.selectedVehicles && ids.length === this.selectedVehicles.length && ids.every((v, i) => v === this.selectedVehicles[i])) return;
            console.log('p-vehicles.handleSelectionChange: ', ids);
            this.$store.commit(enums.DESELECT_VEHICLES_ALL, ids);
            this.$emit('selectionChange', ids);
        },
        // Trigger from vuex
        toggleRowSelection(ids) {
            console.log('p-vehicles.toggleRowSelection: ', ids);
            this.$refs.vTable.toggleRowSelection(ids);
        },
        handleClearIds() {
            this.$store.commit(enums.DESELECT_VEHICLES_ALL);
        },
        // opts callback
        handleDetail(e, row) {
            // this.$router.push({ name: 'vehicle-detail', params: { type: 'read', ids: [row.id] } });
            this.$router.push({ name: 'vehicle-detail', params: { type: 'read', id: row.id } });
        },
        handleModify(e, row) {
            // this.$router.push({ name: 'vehicle-detail', params: { type: 'mod', ids: [row.id] } });
            this.$router.push({ name: 'vehicle-detail', params: { type: 'mod', id: row.id } });
        },
        handleLock(e, row) {
            this.$refs.btns.handleLock(e, [row.id]);
        },
        handleDelete(e, row) {
            this.$refs.btns.handleDelete(e, [row.id]);
        }
    }
};
</script>

<style lang="scss">
.page-vehicles {
}
</style>
